/*
 * @Author: xiaosihan 
 * @Date: 2024-08-20 15:43:42 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-01 13:01:25
 */

import utils from "@utils";
import JSZip from "jszip";
import { Object3D } from "three";
//@ts-ignore
import GLTFExporter from "./GLTFExporter.es.js";
// import { GLTFExporter } from "three/examples/jsm/Addons.js";

const gltfExporter = new GLTFExporter();

// 导出模型
export default function exportGlTF(Object3d: Object3D) {
    return new Promise<ArrayBuffer>(async (resolve, reject) => {
        const gltfjson = await gltfExporter.parseAsync(Object3d, {
            trs: true,
            onlyVisible: true,
            truncateDrawRange: true,
            binary: false,
            embedImages: true, // 内嵌纹理
            maxTextureSize: 1024,
            animations: Object3d.animations,
            forceIndices: false, // 为几何体生成索引
            includeCustomExtensions: false
        }) as { [key: string]: any; };

        // 创建一个新的JSZip实例  
        var zip = new JSZip();

        gltfjson.buffers &&
            gltfjson.buffers.map((buffer: any, i: any) => {
                const name = `${utils.uuid()}.bin`;
                zip.file(name, buffer.uri.split(',')[1], { base64: true }); // 假设imgData是图片的base64编码  
                buffer.uri = name;
            });

        gltfjson.images &&
            gltfjson.images.map((image: any, i: any) => {
                var suffix = image.uri.match(/data:image\/([^;]+);base64,/i)[1].toLowerCase();
                const name = `${utils.uuid()}.${suffix}`;
                zip.file(name, image.uri.split(',')[1], { base64: true }); // 假设imgData是图片的base64编码  
                image.uri = name;
            });

        // 最后把 gltf json 加入到zip
        zip.file(`${utils.uuid()}.gltf`, JSON.stringify(gltfjson, null, 2));

        // 生成ZIP文件并转换为ArrayBuffer  
        const zipArrayBuffer = await zip.generateAsync({ type: "arraybuffer" })

        resolve(zipArrayBuffer as ArrayBuffer);
    });
}